#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
import time
from urllib import request
import tornado.web
class WechatHandler(tornado.web.RequestHandler):
    def get(self):
        url = self.request.protocol + "://" + self.request.host + self.request.uri
        self.render('wechat/index.html', cur_url=url)


class WeixinContentHandler(tornado.web.RequestHandler):
    def get(self):
        key = self.get_argument('key')
        url = self.get_argument('url')
        data = {'code': 400}
        if key != '1234':
            data['msg'] = '输入网址不合法1'
            return self.finish(data)
        if(self._is_weixin_url(url) == False):
            data['msg'] = '网址不合法'
            return self.finish(data)
        req = request.Request(url=url)
        response = request.urlopen(req)
        html_content = response.read().decode("utf-8")
        error_msg = '没有抓取到内容，请拖到尾部，点击邮箱，帮忙报错!'
        data['msg'] = error_msg
        if(not html_content):
            data['code'] = 404
            return self.finish(data)

        cln = self._get_column(html_content)
        if(not cln):
            return data
        data['code'] = 200
        data['msg'] = 'ok'
        data['data'] = cln
        return self.finish(data)

    def _is_weixin_url(self, url = ''):
        '''
        判断是否是符合微信url
        :param url:
        :return:
        '''
        val_url = url.strip()
        patter = re.compile(r'^(https|http)://mp.weixin.qq.com/s/[a-zA-Z0-9\_\-]{10,30}$', flags=re.IGNORECASE)
        data = patter.match(url)
        if(data):
            return True
        else:
            return False

    def _get_column(self, content = ''):
        '''
            获取内容
        :param content:
        :return:
        '''
        html = content.strip()
        if(html == ""):
            return {}

        # nickname
        reg_array = {
            'reg': [
                'var nickname = ".*?"',
                'var ct = ".*?"',
                'var ori_head_img_url = ".*?"',
                'var msg_title = ".*?"',
                'var msg_desc = ".*?"',
                'var msg_cdn_url = ".*?"'
            ],
            'replace': [
                ['var nickname = "', '"'],
                ['var ct = "', '"'],
                ['var ori_head_img_url = "', '"'],
                ['var msg_title = "', '"'],
                ['var msg_desc = "', '"'],
                ['var msg_cdn_url = "', '"']
            ]
        }
        native = []
        for i in reg_array['reg']:
            tmp = re.findall(i, html)
            if(tmp):
                native.append(tmp[0])
        if(len(native) != len(reg_array['replace'])):
            return {}

        want = {}
        for key,value in enumerate(reg_array['replace']):
            tmp = native[key].replace(value[0],'')
            data = tmp.replace(value[1], '')
            if(key == 0):
                want['nickname'] = data
            elif(key == 1):
                struct_time = time.localtime(float(data))
                want['ct'] = time.strftime("%Y-%m-%d %H:%I", struct_time)
            elif(key == 2):
                want['head_url'] = data
            elif(key == 3):
                want['title'] = data
            elif(key == 4):
                want['desc'] = data
            elif(key == 5):
                want['cdn_url'] = data
        return want